<template>
  <div class="storeTour">
    <div class="btGroup">
      <el-button size="mini" type="primary" round @click="addTask">新增任务</el-button>
    </div>

    <div class="table">
      <el-table :data="tableData" size="mini" v-loading="loading">
        <el-table-column label="序号" width="60" type="index" align="center"></el-table-column>
        <el-table-column label="任务名称" align="center" prop="taskName"></el-table-column>
        <el-table-column label="下发门店" align="center" prop="orgsName"></el-table-column>
        <el-table-column label="执行时间" align="center" prop="performTime"></el-table-column>
        <el-table-column label="状态" align="center" prop="isUser">
          <template slot-scope="scope">已{{scope.row.isUser==='0'?'关闭':'开启'}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" round @click="edit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" round @click="handleDelete(scope.row)">删除</el-button>
            <el-button
              size="mini"
              round
              @click="open(scope.row)"
            >{{scope.row.isUser==='1'?'关闭':'开启'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="paging">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10, 20, 30, 50, 100]"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog title="新增任务" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false">
      <el-form
        class="smartShopDialogForm"
        :model="formData"
        :label-position="'right'"
        label-width="80px"
        ref="addStoreInspectionTaskSetting"
        :rules="rules"
      >
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="formData.taskName"></el-input>
        </el-form-item>

        <el-form-item label="下发门店" prop="takeInStore">
          <el-select
            v-model="formData.takeInStore"
            filterable
            allow-create
            placeholder="请选择下发门店"
            multiple
            style="width: 100%"
            value-key="orgSeq"
          >
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :value="{orgSeq:item.orgSeq,orgName:item.orgName}"
              :label="item.orgName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="巡查项" prop="checkItem">
          <el-select v-model="formData.checkItem" placeholder="请选择巡查项">
            <el-option
              v-for="(item,index) in busOptions"
              :key="index"
              :label="item.labelName"
              :value="item.busType"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="执行时间" prop="startTime">
          <el-checkbox-group v-model="formData.startTime" size="mini">
            <el-checkbox
              style="width: 60px"
              v-for="(item,index) in 24"
              :label="(index<10 ? `0${index}` : index)+':00'"
              :key="index"
            ></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="submitTask" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改任务执行时间" :visible.sync="editBox" width="40%" :close-on-click-modal="false">
      <el-checkbox-group style="line-height: 40px" v-model="editTime" size="mini">
        <el-checkbox
          style="width: 60px"
          v-for="(item,index) in 24"
          :label="(index<10 ? `0${index}` : index)+':00'"
          :key="item"
        ></el-checkbox>
      </el-checkbox-group>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editBox = false" size="mini" round>取 消</el-button>
        <el-button type="primary" @click="submitEdit" size="mini" round>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStoreInspectionTaskSettingData,
  setStoreInspectionTaskSettingState,
  queryOrgChildById,
  addStoreInspectionTaskSetting,
  editStoreInspectionTaskSetting,
  realDelPatrol
} from "@/api/smartShops";

export default {
  name: "Index",
  data() {
    return {
      busOptions: [{ busType: 1, labelName: "陈列" }],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      loading: false,
      options: [],
      formData: {
        taskName: "",
        takeInStore: [],
        checkItem: "",
        startTime: [],
        corn: ""
      },
      editTime: [],
      rules: {
        taskName: [
          { required: true, message: "请输入任务名称", trigger: "blur" }
        ],
        takeInStore: [
          { required: true, message: "请勾选下发门店", trigger: "blur" }
        ],
        checkItem: [
          { required: true, message: "请选择巡查项", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "请选择执行时间", trigger: "blur" }
        ]
      },
      editBox: false,
      editData: {}
    };
  },
  methods: {
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData();
    },
    handleCurrentChange(current) {
      this.currentPage = current;
      this.getData();
    },
    addTask() {
      this.dialogVisible = true;
      this.getOptions();
      this.formData = {
        taskName: "",
        takeInStore: [],
        checkItem: "",
        startTime: [],
        corn: ""
      };
    },
    submitTask() {
      this.$refs["addStoreInspectionTaskSetting"].validate(async valid => {
        if (valid) {
          let time = this.formData.startTime.map(item => item.split(":")[0]);
          time.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
          let corn = `0 0 ${time.join(",")} * * ?`;
          let { data } = await addStoreInspectionTaskSetting({
            taskName: this.formData.taskName,
            performTime: this.formData.startTime.join(","),
            performCorn: corn,
            orgsUuid: this.formData.takeInStore.map(item => item.orgSeq),
            orgsName: this.formData.takeInStore.map(item => item.orgName),
            busType: this.formData.checkItem
          });
          this.dialogVisible = false;
        }
        this.getData();
      });
    },
    async open(row) {
      let params = Object.assign({}, row);
      this.$set(
        params,
        "isUser",
        (params.isUser = params.isUser === "0" ? "1" : "0")
      );
      let data = await setStoreInspectionTaskSettingState(params);
      if (data.code) {
        row.isUser = row.isUser === "0" ? "1" : "0";
        this.$message({
          type: "success",
          message: "修改成功"
        });
        return;
      }
      this.$message({
        type: "error",
        message: "修改失败"
      });
    },
    async getData() {
      let { records, total } = await getStoreInspectionTaskSettingData({
        size: this.pageSize,
        current: this.currentPage,
        condition: {
          orgSeq: JSON.parse(localStorage.getItem("logininfo"))["orgList"][0]
            .orgSeq
        }
      });
      if (records) {
        this.tableData = records;
      }
      this.loading = false;
      this.total = total;
    },
    async getOptions() {
      let { records } = await queryOrgChildById({
        orgSeq: JSON.parse(localStorage.getItem("logininfo"))["orgList"][0]
          .orgSeq
      });
      this.options = records;
    },
    edit(row) {
      this.editTime = row.performTime.split(",");
      this.editBox = true;
      this.editData = { ...row };
    },
    handleDelete(row) {
      this.$confirm("是否确认删除该条?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        offset: 160
      })
        .then(async () => {
          let result = await realDelPatrol({ taskUuid: row.taskUuid });
          if (result.code == 1) {
            this.$message({
              type: "success",
              message: "删除成功!",
              duration: 1500
            });
            this.getData();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async submitEdit() {
      let time = this.editTime.map(item => item.split(":")[0]);
      time.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
      let corn = `0 0 ${time.join(",")} * * ?`;
      let { code } = await editStoreInspectionTaskSetting({
        taskUuid: this.editData.taskUuid,
        performTime: this.editTime.join(","),
        performCorn: corn
      });
      if (code === 1) {
        this.editBox = false;
        this.$message({
          type: "success",
          message: "修改成功",
          duration: 1000
        });
        this.getData();
      } else {
        this.$message({
          type: "error",
          message: "修改失败",
          duration: 1000
        });
        this.$router.go(-1);
      }
    }
  },
  created() {
    this.getData();
  }
};
</script>

<style scoped lang="scss">
.storeTour {
  width: 100%;
  height: 100%;
  box-sizing: border-box;

  .btGroup {
    height: 50px;
    width: 100%;
    line-height: 50px;
    border-bottom: 1px solid #dcdfe6;
  }

  .table {
    padding: 10px 0;
    width: 100%;
    max-height: calc(100% - 100px);
  }

  .paging {
    height: 50px;
    width: 100%;
    line-height: 50px;
  }
}
</style>
